package dev.mcdd.validation;


import dev.mcdd.common.json.JsonVo;
import dev.mcdd.common.json.ResponseType;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Path;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Set;

/**
 * @author mcdd1024
 * @name ValidationExceptionHandler
 * @since 2025/1/24 19:11
 */
@RestControllerAdvice
public class ValidationExceptionHandler {

	@ExceptionHandler({BindException.class})
	public JsonVo handlerBindException(BindException bindException) {
		JsonVo vo = JsonVo.error("数据参数错误", ResponseType.CLIENT_ERROR);
		List<FieldError> fieldErrors = bindException.getFieldErrors();
		for (FieldError fieldError : fieldErrors) {
			String field = fieldError.getField();
			String message = fieldError.getDefaultMessage();
			vo.add(field, message);
		}
		return vo;
	}

	@ExceptionHandler({ConstraintViolationException.class})
	public JsonVo handlerConstraintViolationException(ConstraintViolationException cve) {
		Set<ConstraintViolation<?>> violations = cve.getConstraintViolations();
		JsonVo vo = JsonVo.error("数据参数错误", ResponseType.CLIENT_ERROR);
		for (ConstraintViolation<?> violation : violations) {
			Path path = violation.getPropertyPath();
			String message = violation.getMessage();
			Path.Node lastNode = null;
			for (Path.Node node : path) {
				lastNode = node;
			}
			assert lastNode != null;
			vo.add(lastNode.getName(), message);
		}
		return vo;
	}

}
